package com.qys.livesMall.app.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qys.livesMall.app.user.event.ChannelEditEvent;
import com.qys.livesMall.app.user.mapper.UserStatisticsTeamMapper;
import com.qys.livesMall.app.user.model.dto.sys.ChannelEditShopDTO;
import com.qys.livesMall.app.user.model.dto.sys.SysUserChannelEditDTO;
import com.qys.livesMall.app.user.model.entity.*;
import com.qys.livesMall.app.user.scheduledTask.UserStatisticsInfoScheduledTask;
import com.qys.livesMall.app.user.service.*;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ChannelServiceImpl implements IChannelService {
    @Resource
    private UserStatisticsInfoService userStatisticsInfoService;
    @Resource
    private IH2AppUserService ih2AppUserService;
    @Resource
    private UserShopStatisticsService userShopStatisticsService;
    @Resource
    private AppUserRelationService relationService;
    @Resource
    private UserStatisticsInfoScheduledTask userStatisticsInfoScheduledTask;
    @Resource
    private  ApplicationContext applicationContext;
    @Resource
    private UserStatisticsTeamMapper userStatisticsTeamMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean channelEdit(SysUserChannelEditDTO dto) {
        H2AppUser newH2AppUser = ih2AppUserService.getById(dto.getNewUserid());
        //用户统计表
        UserStatisticsInfo newUserStatisticsInfo=userStatisticsInfoService.selectByUserId(dto.getNewUserid());
        if (null==newUserStatisticsInfo){return null;}
        //公共表
        UserShopStatistics newUserStatistics =userShopStatisticsService.selectByUserId(newUserStatisticsInfo.getUserId());
        UserShopStatistics oldUserStatistics =userShopStatisticsService.selectByUserId(dto.getOldUserId());

        //用户子集和自己 的用户ID
        List<Long> userIds=new ArrayList<>();
        List<H2AppUser> h2AppUsers= relationService.getLowerLevels(dto.getOldUserId());
        if (CollectionUtils.isNotEmpty(h2AppUsers)){
            userIds.addAll(h2AppUsers.stream().map(a->Long.valueOf(a.getId())).toList());
        }
        userIds.add(dto.getOldUserId());
        //用户信息
        LambdaQueryWrapper<UserShopStatistics> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.in(UserShopStatistics::getUserId,userIds);
        List<UserShopStatistics> userStatistics = userShopStatisticsService.list(queryWrapper);

        //1：变更用层级
        convertStorey(userStatistics,userStatistics.get(0).getStorey(), Arrays.asList(dto.getOldUserId()));
        //2：变更用户渠道
        convertUserStatistics(userStatistics,newUserStatistics,dto.getOldUserId());

        H2AppUser h2AppUser=ih2AppUserService.getById(dto.getOldUserId());
        h2AppUser.setSuperior(Long.valueOf(newH2AppUser.getId()));
        h2AppUser.setSuperiorName(newH2AppUser.getNickName());
        ih2AppUserService.updateById(h2AppUser);
        //更新用户上级
        userShopStatisticsService.updateBatchById(userStatistics);
        //移动关系
        relationService.remove(Long.valueOf(h2AppUser.getId()));
        //更新团数据
        userStatisticsInfoScheduledTask.updateUserTeam(Arrays.asList(newUserStatistics.getTeamId(),oldUserStatistics.getTeamId()));
        userIds.add(dto.getNewUserid());
        userStatisticsInfoScheduledTask.updateUserSubordinateInfo(userIds);
        userStatisticsInfoScheduledTask.updateUserStatisticsInfo(userIds);

        //更新店铺团数据
        List<Long> shopIds=userShopStatisticsService.getShopIdsByTeamId(Arrays.asList(newUserStatistics.getTeamId(),oldUserStatistics.getTeamId()));
        if (CollectionUtils.isNotEmpty(shopIds)){
            ChannelEditShopDTO channelEditShopDTO=new ChannelEditShopDTO();
            channelEditShopDTO.setShopIds(shopIds);
            applicationContext.publishEvent(new ChannelEditEvent(channelEditShopDTO));
        }
        if (h2AppUser.getUserSysType()==2){
            userStatisticsTeamMapper.deleteBYteamId(h2AppUser.getId());
        }
        return true;
    }
    /**
     * 变更渠道
     *
     * @param userStatistics 需要变更用户数据
     * @param userShopStatistics 新上级用户信息
     * @param oldUserId 变更的旧用户ID
     */
    private void convertUserStatistics(List<UserShopStatistics> userStatistics, UserShopStatistics userShopStatistics, Long oldUserId) {
        if (null==userStatistics){
            return;
        }
        H2AppUser h2AppUser=ih2AppUserService.getById(userShopStatistics.getUserId());
        for (UserShopStatistics statistics:userStatistics){
            if (statistics.getUserId().equals(oldUserId)){
                statistics.setSuperior(h2AppUser.getUserName());
            }
            statistics.setAgentAccount(userShopStatistics.getAgentAccount());
            statistics.setTeamId(userShopStatistics.getTeamId());
        }
    }


    /**
     * 转换用户层级
     * @param userStatistics
     * @param storey
     * @param oldUserIds
     */
    private void convertStorey(List<UserShopStatistics> userStatistics, Integer storey, List<Long> oldUserIds) {
        //变更oldUserIds 下级层级
        for (UserShopStatistics statisticsInfo:userStatistics){
            if (oldUserIds.contains(statisticsInfo.getUserId())){
                statisticsInfo.setStorey(storey+1);
            }
        }
        //获取oldUserIds 下级
        List<Long> newUserids=new ArrayList<>();
        for (UserShopStatistics statisticsInfo:userStatistics){
            if (oldUserIds.contains(statisticsInfo.getSuperior())){
                newUserids.add(statisticsInfo.getUserId());
            }
        }
        //递归
        if (CollectionUtils.isNotEmpty(newUserids)){
            convertStorey(userStatistics,storey+1,newUserids);
        }
    }
}
